package org.xjtu.weteam.common.utils;

import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.UUID;

public class imageUtil {

    public static String saveAvatarFile(MultipartFile file) throws IOException {
        File dir = new File("./file/image/");
        String realPath = dir.getCanonicalPath();
        String filename = file.getOriginalFilename();
        String fileExtension = filename.substring(filename.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
        File targetFile = new File(realPath + "\\" + uniqueFileName);
        file.transferTo(targetFile);
        return uniqueFileName;
    }

    public static String getAvatar(String imagePath) throws IOException {
        File dir = new File("./file/image/");
        String basePath = dir.getCanonicalPath();
        File file = new File(basePath + File.separator + imagePath);

        if (!file.exists()) {
            throw new IOException("图片文件不存在: " + imagePath);
        }

        String base64Image = convertImageToBase64(new FileInputStream(file));
        return base64Image;
    }
    // 辅助方法：将 InputStream 转换为 Base64 字符串
    private static String convertImageToBase64(FileInputStream fis) throws IOException {
        try {
            // 读取图片数据
            byte[] imageBytes = fis.readAllBytes();
            // 转换为 Base64
            return Base64.getEncoder().encodeToString(imageBytes);
        } finally {
            fis.close();  // 确保关闭输入流
        }
    }

}
